;
(function(factory) {
	if(typeof define === 'function' && define.amd) {
		define(['jquery', 'math', 'bootstrap', 'bDialog', 'vw.searchtree', 'vw.static'], factory);
	} else {
		if(typeof module === 'object' && module.exports) {
			//
		} else {
			factory(window.jQuery, math);
		}
	}
})(function($, math) {
	'use strict';
	var pluginName = "vw_bindreport";
	var defaults = {
		$container: null,
		height: 95,
		heightDiff: 95,
		htmlPath: "html/",
		dataURL: "",
		saveURL: "",
		labelColor: "#FF0000",
		bindHeaderColor: "#f0ad4e",
		bindBodyColor: "#5cb85c",
		bindColTagColor: "#337ab7",
		selectColor: "#CAE1FF",
		highlightColor: "#FFFF00",
		mousemoveColor: "#F0FFF0",
		dataResponseName: 'columns',
		positionName: "F_CELL_POSITION",
		headerName: "F_IS_HEADER",
		mathName: "F_MATH",
		extrapara: {}
	};

	var methods = [
		'ajaxLoadReport',
		'destroy',
		'getBindData',
		'getOptions'
	];

	var DIV_SELECT = "class-sel";
	var DIV_BIND_BODY = "class-bind-body";
	var DIV_BIND_HEADER = "class-bind-header";
	var DIV_HIGHLIGHT = "class-hightlight";
	var DIV_MOVE = "class-move";
	var POSITION_SPLIT = ";";
	var MATH_SPLIT = ";";
	var TAG_FN = "公式";
	var TAG_POSITION_BODY = "表体";
	var TAG_POSITION_HEADER = "表头";
	var COLOR_TAG_FN = '#5bc0de';
	var COLOR_TAG_POSITION_BODY = defaults.bindBodyColor;
	var COLOR_TAG_POSITION_HEADER = defaults.bindHeaderColor;

	var vw_bindreport = function(element, options) {
		this.$element = $(element);
		this.options = $.extend({}, defaults, options);
		this._defaults = defaults;
		this._name = pluginName + this.$element.attr('id');
		this.version = 'v1.0.0';
		this._defineCustomObjectandEvents();
		this._init();
	}

	vw_bindreport.prototype = {
		_defineCustomObjectandEvents: function() {
			var that = this;

			function obj_bindData() {
				this.loadData = function(data) {
					$.each(data, function(i, col) {
						col.pid = -1;
						col.text = col.title;
						col.tags = [];
						if(col.cellposition) {
							col.cells = col.cellposition.split(POSITION_SPLIT);
							if(col.header) {
								col.tags.push(TAG_POSITION_HEADER);
								$.each(col.cells, function(k, val) {
									that.$frame.find('td[id="' + val + '"]').addClass(DIV_BIND_HEADER);
								});
							} else {
								col.tags.push(TAG_POSITION_BODY);
								$.each(col.cells, function(k, val) {
									that.$frame.find('td[id="' + val + '"]').addClass(DIV_BIND_BODY);
								});
							}
						} else {
							col.cells = null;
						}
						if(col.math) {
							col.math = JSON.parse(vw_static.uncompileStr(col.math));
							col.tags.push(TAG_FN);
						}
					});
					this.data = data;
					that._edited.resetData();
					this.propertyChange(this.data);
				}
				this.setCells = function(id, cells, callback) {
					$.each(this.data, function(k, col) {
						if(id == col.id) {
							if(col.cells) {
								$.each(col.cells, function(k, val) {
									that.$frame.find('td[id="' + val + '"]').removeClass(DIV_BIND_HEADER).removeClass(DIV_BIND_BODY);
								});
							}
							col.tags = [];
							if(col.math) {
								col.tags.push(TAG_FN);
							}
							col.cells = cells;
							col.cellposition = "";

							if(cells) {
								col.cellposition = cells.join(POSITION_SPLIT);
								if(col.header) {
									col.tags.push(TAG_POSITION_HEADER);
									$.each(col.cells, function(k, val) {
										that.$frame.find('td[id="' + val + '"]').addClass(DIV_BIND_HEADER);
									});
								} else {
									col.tags.push(TAG_POSITION_BODY);
									$.each(col.cells, function(k, val) {
										that.$frame.find('td[id="' + val + '"]').addClass(DIV_BIND_BODY);
									});
								}
							}
							if(callback) {
								callback(col);
							}
							return true;
						}
					});

					this.propertyChange(this.data);
				}
				this.setMath = function(id, math, callback) {
					$.each(this.data, function(k, col) {
						if(id == col.id) {
							col.tags = [];
							col.math = math;
							if(col.cells) {
								if(col.header) {
									col.tags.push(TAG_POSITION_HEADER);
								} else {
									col.tags.push(TAG_POSITION_BODY);
								}
							}
							if(math) {
								col.tags.push(TAG_FN);
							}
							if(callback) {
								callback(col);
							}
							return true;
						}
					});

					this.propertyChange(this.data);
				}
				this.deleteBind = function(id, callback) {
					$.each(this.data, function(k, col) {
						if(id == col.id) {
							col.tags = [];
							col.math = null;
							col.cells = null;
							col.cellposition = "";
							if(callback) {
								callback(col);
							}
							return true;
						}
					});

					this.propertyChange(this.data);
				}
			};

			obj_bindData.prototype = {
				propertyChange: function(value) {
					that._refreshTree();
				}
			};

			function obj_selectedCells() {
				this.setData = function() {
					this.data = [];
					var thatdata = this.data;
					$.each(that.$frame.find('.' + DIV_SELECT), function(k, val) {
						thatdata.push($(val).attr('id'));
					});
					this.propertyChange(this.data);
				}
				this.resetData = function() {
					this.data = [];
					that.$frame.find('.' + DIV_SELECT).removeClass(DIV_SELECT);
					that._renderAllCell();
					this.propertyChange(this.data);
				}
			};

			obj_selectedCells.prototype = {
				propertyChange: function(value) {
					that.$fnBind.prop('disabled', !(value.length && that._curCol.column));
				}
			};

			function obj_curCol() {
				this.setData = function(col) {
					that.$frame.find('.' + DIV_HIGHLIGHT).removeClass(DIV_HIGHLIGHT);
					var curCol;
					$.each(that._bindData.data, function(k, val) {
						if(col == val.id) {
							curCol = val;
							return true;
						}
					});

					if(curCol.cells) {
						$.each(curCol.cells, function(k, val) {
							that.$frame.find('td[id="' + val + '"]').addClass(DIV_HIGHLIGHT);
						});

						if(curCol.cells.length == 1) {
							this.math.target = "[" + curCol.cells[0] + "]";
						} else {
							this.math.target = "{" + curCol.title + "}";
						}

						if(curCol.math) {
							this.math.expr = curCol.math.expr;
						}
					}

					this.column = curCol;
					this.propertyChange(this.column);
				}
				this.resetData = function() {
					this.column = null;
					this.math = {
						target: "未选择",
						expr: []
					};
					that.$frame.find('.' + DIV_HIGHLIGHT).removeClass(DIV_HIGHLIGHT);
					this.propertyChange(this.column);
				}
			};

			obj_curCol.prototype = {
				propertyChange: function(value) {
					that._renderAllCell();
					that.$fnBind.prop('disabled', !(that._selCells.data.length && value));
					that.$fnDelete.prop('disabled', !(value && value.cells));
				}
			};

			function obj_editedCells() {
				this.bindCell = function() {
					that.$frame.find('.' + DIV_HIGHLIGHT).removeClass(DIV_HIGHLIGHT);
					$.each(that._selCells.data, function(k, val) {
						that.$frame.find('td[id="' + val + '"]').addClass(DIV_HIGHLIGHT);
						that.$frame.find('td[id="' + val + '"]').removeClass(DIV_SELECT);
					});

					var thatdata = this.data;
					that._bindData.setCells(that._curCol.column.id, that._selCells.data, function(editCol) {
						var flag = false;
						$.each(thatdata, function(k, val) {
							if(val.F_ID == editCol.id && val.F_CODE == that.options.positionName) {
								val.F_VALUE = editCol.cellposition;
								flag = true;
								return true;
							}
							if(val.F_ID == editCol.id && val.F_CODE == that.options.headerName) {
								val.F_VALUE = editCol.header ? 1 : 0;
								flag = true;
								return true;
							}
						});
						if(!flag) {
							thatdata.push({
								F_TEXT: editCol.title,
								F_CODE: that.options.positionName,
								F_VALUE: editCol.cellposition,
								F_ID: editCol.id
							});
							thatdata.push({
								F_TEXT: editCol.title,
								F_CODE: that.options.headerName,
								F_VALUE: editCol.header ? 1 : 0,
								F_ID: editCol.id
							});
						}
					});

					this.propertyChange(this.data);
				}
				this.saveMath = function() {
					if(that.$inputExpr.val()) {
						if(!that._curCol.math) {
							that._curCol.math = {}
						}
						that._curCol.math.target = that.$exprTarget.text();
						that._curCol.math.expr = vw_static.SBCtoDBC(that.$inputExpr.val()).split(MATH_SPLIT);
					} else {
						that._curCol.math = {
							target: "未选择",
							expr: []
						};
					}
					var thatdata = this.data;
					that._bindData.setMath(that._curCol.column.id, that._curCol.math, function(editCol) {
						var flag = false;
						var codingStr = vw_static.compileStr(JSON.stringify(editCol.math))
						$.each(thatdata, function(k, val) {
							if(val.F_ID == editCol.id && val.F_CODE == that.options.mathName) {
								val.F_VALUE = codingStr;
								flag = true;
								return true;
							}
						});
						if(!flag) {
							thatdata.push({
								F_TEXT: editCol.title,
								F_CODE: that.options.mathName,
								F_VALUE: codingStr,
								F_ID: editCol.id
							});
						}
					});
					this.propertyChange(this.data);
				}
				this.deleteData = function() {
					that.$frame.find('.' + DIV_HIGHLIGHT).removeClass(DIV_BIND_HEADER).removeClass(DIV_BIND_BODY).removeClass(DIV_HIGHLIGHT);

					that._curCol.math = {
						target: "未选择",
						expr: []
					};

					var thatdata = this.data;
					that._bindData.deleteBind(that._curCol.column.id, function(editCol) {
						var flag = false;
						$.each(thatdata, function(k, val) {
							if(val.F_ID == editCol.id) {
								val.F_VALUE = "";
								flag = true;
							}
						});
						if(!flag) {
							thatdata.push({
								F_TEXT: editCol.title,
								F_CODE: that.options.positionName,
								F_VALUE: "",
								F_ID: editCol.id
							});
							thatdata.push({
								F_TEXT: editCol.title,
								F_CODE: that.options.headerName,
								F_VALUE: "",
								F_ID: editCol.id
							});
							thatdata.push({
								F_TEXT: editCol.title,
								F_CODE: that.options.mathName,
								F_VALUE: "",
								F_ID: editCol.id
							});
						}
					});

					this.propertyChange(this.data);
				}
				this.resetData = function() {
					this.data = [];
					that._cancelExpr();
					this.propertyChange(this.data);
				}
			};

			obj_editedCells.prototype = {
				propertyChange: function(value) {
					that.$editnum.text(value.length);
					that.$fnSubmit.prop('disabled', !value.length);
				}
			};

			that._bindData = new obj_bindData();
			that._selCells = new obj_selectedCells();
			that._curCol = new obj_curCol();
			that._edited = new obj_editedCells();
		},

		_init: function() {
			var that = this;
			that.$element.append([
				'<div class="row">',
				'	<div class="col-md-9">',
				'		<form class="form-inline" autocomplete="off">',
				'			<div class="form-group">',
				'				<button type="button" id="' + that._name + '-bind" class="btn btn-primary"><i class="fa fa-braille"></i>  绑定位置</button>',
				'				<button type="button" id="' + that._name + '-delete" class="btn btn-danger"><i class="fa fa-trash"></i>  删除</button>',
				'				<button type="button" id="' + that._name + '-submit" class="btn btn-success"><i class="fa fa-cloud-upload"></i>  提交',
				'				（<span id="' + that._name + '-editnum"></span>）' +
				'				</button>',
				'				<div class="input-group">',
				'					<div class="input-group-addon"><strong>公式：</strong></div>',
				'					<div class="input-group-addon" id="' + that._name + '-expr-target"></div>',
				'					<input type="text" autocomplete="off" readonly class="form-control" id="' + that._name + '-expr" placeholder="双击此处开始编辑公式...">',
				'				</div>',
				'				<button type="button" id="' + that._name + '-cancelexpr" class="btn btn-warning hidden"><i class="fa fa-ban"></i>  取消</button>',
				'				<button type="button" id="' + that._name + '-saveexpr" class="btn btn-success hidden"><i class="fa fa-save"></i>  保存</button>',
				'			</div>',
				'		</form>',
				'		<div class="row">',
				'			<div id="' + that._name + '-frame"></div>',
				'		</div>',
				'	</div>',
				'	<div class="col-md-3">',
				'		<div id="' + that._name + '-searchtree_plus"></div>',
				'	</div>',
				'</div>',
				'<div id="' + that._name + '-coltext"><span class="text-primary"></span></div>'
			].join(""));

			that.$frame = $('#' + that._name + '-frame');
			that.$searchtree = $('#' + that._name + '-searchtree_plus');
			that.$fnBind = $('#' + that._name + '-bind');
			that.$exprTarget = $('#' + that._name + '-expr-target');
			that.$inputExpr = $('#' + that._name + '-expr');
			that.$fnCancelexpr = $('#' + that._name + '-cancelexpr');
			that.$fnSaveExpr = $('#' + that._name + '-saveexpr');
			that.$fnDelete = $('#' + that._name + '-delete');
			that.$fnSubmit = $('#' + that._name + '-submit');
			that.$editnum = $('#' + that._name + '-editnum');
			that.$coltext = $('#' + that._name + '-coltext');

			that.$element.css({
				'margin-top': '10px'
			});

			that.$element.find('button').css({
				'margin-left': '5px'
			});

			that.$inputExpr.css({
				'width': '300px'
			});

			that.$editnum.css({
				'color': 'white'
			});

			that.$frame.css({
				'width': '100%',
				'overflow': 'auto',
				"display": "-webkit-flex",
				"-webkit-justify-content": "center",
				"margin": "15px"
			});

			that.$coltext.css({
				"position": "fixed",
				"color": that.options.bindColTagColor,
				"padding": "5px",
				"border": "solid 1px #ccc",
				"background-color": "#eee",
				"border-radius": "4px"
			});

			that.$coltext.addClass("hidden");

			that.$fnBind.on('click', function() {
				that._bind();
			});

			that.$inputExpr.on('dblclick', function() {
				that._dblClickExpr();
			});

			that.$fnCancelexpr.on('click', function() {
				that._cancelExpr();
			});

			that.$fnSaveExpr.on('click', function() {
				that._saveExpr();
			});

			that.$fnDelete.on('click', function() {
				that._delete();
			});

			that.$fnSubmit.on('click', function() {
				that._submit();
			});

			that.$editnum.text("0");
			that.$fnBind.prop('disabled', true);
			that.$fnSubmit.prop('disabled', true);
			that.$fnDelete.prop('disabled', true);

			resize();
			$(window).resize(resize);

			function resize() {
				var containerHeight;
				if(that.options.$container) {
					containerHeight = that.options.$container.height();
				} else {
					if(that.options.height) {
						containerHeight = that.options.height;
					} else {
						containerHeight = $(window).height();
					}
				}

				that.height = containerHeight - that.options.heightDiff;
				that.$frame.css('height', that.height + "px");
			}
		},

		destroy: function() {
			this.$element.empty();
		},

		getBindData: function() {
			return this._bindData.data;
		},

		getOptions: function() {
			return this.options;
		},

		ajaxLoadReport: function(htmlName) {
			var that = this;
			if(!that.options.dataURL || !htmlName) {
				return;
			}

			that._tableid = htmlName;

			that.$frame.load(that.options.htmlPath + htmlName + ".html", function(response, status) {
				if(status != "success") {
					$.Notify({
						caption: "错误",
						content: "表单文件（" + that.options.htmlPath + htmlName + ".html）加载失败",
						type: "alert"
					});
					return;
				}
				
				that.$frame.find('table').css({
					'width': '99%'
				});

				that.$a = that.$frame.find('td a')
					.css({
						"color": that.options.labelColor,
						"cursor": "default"
					})
					.each(function() {
						var oldID = $(this).parent().attr("id");
						$(this).parent().attr("id", vw_static.idToPosition(oldID));
						$(this).text($(this).parent().attr("id"));
						$(this).parent().attr("align", "center");
					});

				that.options.extrapara.table = that._tableid;
				vw_common.customAjax({
					url: that.options.dataURL,
					type: "GET",
					dataType: "json",
					data: that.options.extrapara
				}, function(e) {
					that._bindData.loadData(e[that.options.dataResponseName]);

					that._bindCellMouseEvent();
					that._bindCurColMouseEvent();
				});
			})
		},

		_renderAllCell: function() {
			var that = this;
			$.each(that.$frame.find('td a'), function(k, val) {
				var $val = $(val).parent();
				if($val.hasClass(DIV_MOVE)) {
					$val.css('background-color', that.options.mousemoveColor);
				} else if($val.hasClass(DIV_SELECT)) {
					$val.css('background-color', that.options.selectColor);
				} else if($val.hasClass(DIV_HIGHLIGHT)) {
					$val.css('background-color', that.options.highlightColor);
				} else if($val.hasClass(DIV_BIND_HEADER)) {
					$val.css('background-color', that.options.bindHeaderColor);
				} else if($val.hasClass(DIV_BIND_BODY)) {
					$val.css('background-color', that.options.bindBodyColor);
				} else {
					$val.css('background-color', '');
				}
			});
		},

		_refreshTree: function() {
			var that = this;
			that.$searchtree.vw_searchtree('destroy').vw_searchtree({
				showEdit: false,
				height: that.height + 45,
				data: that._bindData.data,
				selectFirst: false,
				emptyIcon: "glyphicon glyphicon-info-sign",
				onTreeSelected: function(node) {
					that._curCol.setData(node.id);
					that._cancelExpr();
				},
				onTreeUnselected: function() {
					that._curCol.resetData();
				}
			});

			that.$searchtree.find("span.badge").each(function() {
				switch($(this).text()) {
					case TAG_FN:
						$(this).css('background-color', COLOR_TAG_FN);
						$(this).css('right', "40px");
						break;
					case TAG_POSITION_HEADER:
						$(this).css('background-color', COLOR_TAG_POSITION_HEADER);
						$(this).css('right', "5px");
						break;
					case TAG_POSITION_BODY:
						$(this).css('background-color', COLOR_TAG_POSITION_BODY);
						$(this).css('right', "5px");
						break;
					default:
						break;
				}
			});

			that._selCells.resetData();
			that._curCol.resetData();
		},

		_bindCellMouseEvent: function() {
			var that = this;
			that.$frame.off('mousedown');
			that.$frame.mousedown(function(e) {
				that.$frame.off('mousemove');
				that.$coltext.addClass("hidden");
				var startX = e.pageX;
				var startY = e.pageY;

				that.$frame.mousemove(function(e) {
					var extentSel = {
						left: math.min(e.pageX, startX),
						top: math.min(e.pageY, startY),
						width: math.abs(e.pageX - startX),
						height: math.abs(e.pageY - startY)
					}

					that.$a.each(function() {
						var $td = $(this).parent('td');
						var extentCell = {
							left: $td.offset().left,
							top: $td.offset().top,
							width: $td.width(),
							height: $td.height()
						}
						that._renderEnvelopeSel(vw_static.isIntersect(extentSel, extentCell), $td);
					});
				});

				that.$frame.mouseup(function(e) {
					if(startX == e.pageX && startY == e.pageY) {
						that.$a.each(function() {
							var $td = $(this).parent('td');
							var extentCell = {
								left: $td.offset().left,
								top: $td.offset().top,
								width: $td.width(),
								height: $td.height()
							}

							var a1 = e.pageX >= extentCell.left && e.pageX <= extentCell.left + extentCell.width;
							var a2 = e.pageY >= extentCell.top && e.pageY <= extentCell.top + extentCell.height;
							that._renderEnvelopeSel(a1 && a2, $td);
							return true;
						});
					}
					that._selCells.setData();
					that.$frame.off('mousemove');
					that.$frame.off('mouseup');
					that._bindCurColMouseEvent();
				});
			});
		},

		_bindCurColMouseEvent: function() {
			var that = this;
			that.$frame.off('mousemove');
			that.$frame.mousemove(function(e) {
				that.$frame.find('.' + DIV_MOVE).removeClass(DIV_MOVE);
				that.$coltext.addClass("hidden");

				that.$a.each(function() {
					var $td = $(this).parent('td');
					var extentCell = {
						left: $td.offset().left,
						top: $td.offset().top,
						width: $td.width(),
						height: $td.height()
					}
					var a1 = e.pageX >= extentCell.left && e.pageX <= extentCell.left + extentCell.width;
					var a2 = e.pageY >= extentCell.top && e.pageY <= extentCell.top + extentCell.height;
					if(a1 && a2) {
						$.each(that._bindData.data, function(i, item) {
							if(item.cells && item.cells.indexOf($td.text()) != -1) {
								$.each(item.cells, function(k, val) {
									that.$frame.find('td[id="' + val + '"]').addClass(DIV_MOVE);
								});
								that.$coltext.removeClass("hidden");
								that.$coltext.text(item.title);
								that.$coltext.css({
									"top": e.pageY - that.$coltext.outerHeight(true) - 5 + "px",
									"left": e.pageX - that.$coltext.outerWidth(true) / 2 + "px"
								});
								return false;
							}
						});
					}
				});
				that._renderAllCell();
			});
		},

		_renderEnvelopeSel: function(isSel, $td) {
			var that = this;
			if(isSel) {
				$td.addClass(DIV_SELECT);
				$td.css('background-color', that.options.selectColor);
			} else {
				$td.removeClass(DIV_SELECT);
				if($td.hasClass(DIV_HIGHLIGHT)) {
					$td.css('background-color', that.options.highlightColor);
				} else if($td.hasClass(DIV_BIND_HEADER)) {
					$td.css('background-color', that.options.bindHeaderColor);
				} else if($td.hasClass(DIV_BIND_BODY)) {
					$td.css('background-color', that.options.bindBodyColor);
				} else {
					$td.css('background-color', "");
				}
			}
		},

		_renderSingleSel: function(isSel, $td) {
			var that = this;
			if(isSel) {
				if($td.hasClass(DIV_SELECT)) {
					that._renderSingleSel(false, $td);
					return false;
				} else {
					$td.addClass(DIV_SELECT);
					$td.css('background-color', that.options.selectColor);
					return true;
				}
			} else {
				$td.removeClass(DIV_SELECT);
				if($td.hasClass(DIV_HIGHLIGHT)) {
					$td.css('background-color', that.options.highlightColor);
				} else if($td.hasClass(DIV_BIND_HEADER)) {
					$td.css('background-color', that.options.bindHeaderColor);
				} else if($td.hasClass(DIV_BIND_BODY)) {
					$td.css('background-color', that.options.bindBodyColor);
				} else {
					$td.css('background-color', "");
				}
				return false;
			}
		},

		_bind: function() {
			var that = this;

			var dom = [
				'<div style="padding: 30px 0 0 90px;">',
				'	<label class="radio-inline">',
				'		<input type="radio" name="' + that._name + '_inlineRadioOptions" value="head" checked> 表头',
				'	</label>',
				'	<label class="radio-inline">',
				'		<input type="radio" name="' + that._name + '_inlineRadioOptions" value="body"> 表体',
				'	</label>',
				'</div>'
			].join('');

			bDialog.open({
				title: "绑定类型",
				dom: dom,
				dialogMaxButton: false,
				customClass: 'blue',
				width: 400,
				height: 200,
				fnButton: true,
				fnButtonName: "确定",
				onShow: function(dialog) {
					$(dialog.dialog[0]).find('.radio-inline').css({
						"font-size": "26px",
						"margin-right": "40px",
						"color": "#FFFFFF",
						"padding": "5px 10px",
						"border-radius": "10px"
					});

					$($(dialog.dialog[0]).find('.radio-inline')[0]).css({
						"background-color": that.options.bindHeaderColor
					});

					$($(dialog.dialog[0]).find('.radio-inline')[1]).css({
						"background-color": that.options.bindBodyColor
					});

					$(dialog.dialog[0]).find('input[type=radio]').css({
						"margin-top": "12px",
						"margin-left": "-30px"
					});
				},
				fn: function() {
					bDialog.close({
						result: $("input[name='" + that._name + "_inlineRadioOptions']:checked").val()
					});
				},
				callback: function(data) {
					if(data.results != null) {
						that._curCol.column.header = data.results[0].result == "head" ? true : false;
						that._edited.bindCell();

						$.Notify({
							caption: "提示",
							content: "位置绑定已加入变更列表，提交后生效。",
							type: "info"
						});
					}
				},
			}, {
				messageType: 'confirm',
				cancel: function() {}
			});
		},

		_delete: function() {
			var that = this;
			bDialog.alert('将连同绑定的公式一并删除，确定删除吗？', function() {
				that._edited.deleteData();

				$.Notify({
					caption: "提示",
					content: "删除数据已加入变更列表，提交后生效。",
					type: "info"
				});
			}, {
				messageType: 'confirm',
				cancel: function() {}
			});
		},

		_dblClickExpr: function() {
			var that = this;
			if(!that._curCol.column) {
				$.Notify({
					caption: "提示",
					content: "请先选择指标",
					type: "warning"
				});

				return;
			}

			that.$inputExpr.attr('readonly', false);
			that.$fnCancelexpr.removeClass('hidden');
			that.$fnSaveExpr.removeClass('hidden');

			that._selCells.resetData();

			that.$frame.off('mousemove');
			that.$frame.off('mousedown');
			that.$frame.mousedown(function(e) {
				var startX = e.pageX;
				var startY = e.pageY;

				that.$frame.mouseup(function(e) {
					if(startX == e.pageX && startY == e.pageY) {
						that.$a.each(function() {
							var $td = $(this).parent('td');
							var extentCell = {
								left: $td.offset().left,
								top: $td.offset().top,
								width: $td.width(),
								height: $td.height()
							}

							var a1 = e.pageX >= extentCell.left && e.pageX <= extentCell.left + extentCell.width;
							var a2 = e.pageY >= extentCell.top && e.pageY <= extentCell.top + extentCell.height;
							if(that._renderSingleSel(a1 && a2, $td)) {
								that.$inputExpr.val(that.$inputExpr.val() + "[" + $td.attr("id") + "]");
							}
						});
					}
					that.$frame.off('mouseup');
				});
			});
		},

		_cancelExpr: function() {
			var that = this;
			that._bindCurColMouseEvent();
			that._bindCellMouseEvent();

			that.$fnCancelexpr.addClass('hidden');
			that.$fnSaveExpr.addClass('hidden');
			if(that._curCol.math) {
				that.$exprTarget.text(that._curCol.math.target);
				that.$inputExpr.val(that._curCol.math.expr.join(MATH_SPLIT));
			}
			that.$inputExpr.attr('readonly', true);
		},

		_saveExpr: function() {
			this._edited.saveMath();
			this._cancelExpr();
		},

		_submit: function() {
			var that = this;
			if(!that.options.saveURL) {
				return;
			}

			bDialog.alert('确认保存这些数据吗？', function() {
				vw_common.customAjax({
					url: that.options.saveURL,
					type: "POST",
					dataType: "json",
					data: {
						table: that._tableid,
						data: JSON.stringify({
							data: that._edited.data
						}),
						extrapara: JSON.stringify(that.options.extrapara)
					}
				}, function() {
					that._edited.resetData();

					$.Notify({
						caption: "成功",
						content: "数据保存成功",
						type: "success"
					});
				});
			}, {
				messageType: 'confirm',
				cancel: function() {}
			});
		}
	}

	$.fn[pluginName] = function(option) {
		var value;
		var args = Array.prototype.slice.call(arguments, 1);
		this.each(function() {
			var $this = $(this);
			var data = $this.data(pluginName);
			if(typeof option === 'string') {
				if($.inArray(option, methods) < 0) {
					throw new Error("该方法不存在: " + option);
				}
				if(!data) {
					return;
				}
				value = data[option].apply(data, args);
				if(option === 'destroy') {
					$this.removeData(pluginName);
				}
			}
			if(!data) {
				$this.data(pluginName, (data = new vw_bindreport(this, option)));
			}
		});
		return typeof value === 'undefined' ? this : value;
	};
});